"""
Case Type   : SQL语法
Case Name   : opengauss关键字(非保留)，作为目录对象名
Create At   : 2023/05/11
Owner       : cr13
Description :
    1.关键字做目录对象名不带双引号
    2.关键字做目录对象名带双引号
    3.关键字做目录对象名带单引号
    4.关键字做目录对象名带反引号
    5.清理环境
Expect      :
    1.成功
    2.成功
    3.合理报错
    4.合理报错
    5.成功
History     :
"""

import os
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class SQL(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.commsh = CommonSH('PrimaryDbUser')

    def test_keywords_alias(self):
        text = "----step1:关键字做目录对象名不带双引号 expect:成功----"
        self.log.info(text)
        sql_cmd = f"drop directory if exists alias;create directory " \
            f"alias as '/tmp/';"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.DROP_DIRECTORY_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.CREATE_DIRECTORY_SUCCESS_MSG, result,
                      '执行失败' + text)

        text = "----step2:关键字做目录对象名带双引号 expect:成功----"
        self.log.info(text)
        sql_cmd = f'''drop directory if exists "alias";create directory 
            "alias" as '/tmp/'; '''
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.DROP_DIRECTORY_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.CREATE_DIRECTORY_SUCCESS_MSG, result,
                      '执行失败' + text)

        text = "----step3:关键字做目录对象名带单引号 expect:合理报错----"
        self.log.info(text)
        sql_cmd = f"drop directory if exists 'alias';create directory " \
            f"'alias' as '/tmp/';"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        flg = '''ERROR:  syntax error at or near "'alias'"'''
        self.assertEqual(result.count(flg), 2, '执行失败' + text)

        text = "----step4:关键字做目录对象名带反引号 expect:合理报错----"
        self.log.info(text)
        sql_cmd = f"drop directory if exists \\`alias\\`;create " \
            f"directory \\`alias\\` as '/tmp/';"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        flg = '''ERROR:  syntax error at or near "`"'''
        self.assertEqual(result.count(flg), 2, '执行失败' + text)

    def tearDown(self):
        text = '-----step5:清理环境 expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop directory if exists alias;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.DROP_DIRECTORY_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
